package com.xunwulian.web.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.xunwulian.api.iface.ConfigAPI;
import com.xunwulian.base.dao.UserDao;
import com.xunwulian.base.entity.ConfigEntity;
import com.xunwulian.base.entity.User;
import com.xunwulian.base.util.PageData;
import com.xunwulian.base.util.SysUtils;
import com.xunwulian.web.util.AppUtil;
import com.xunwulian.web.util.Const;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名称：HeadController
 */
@Controller
@RequestMapping(value = "/head")
public class HeadController extends BaseController {

    @Reference
    private ConfigAPI configAPI;

    @Autowired
    private UserDao userDao;

    /**
     * 获取头部信息
     *
     * @return
     */
    @RequestMapping(value = "/getUname")
    @ResponseBody
    public Object getList() {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<User> pdList = new ArrayList();

            //shiro管理的session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();

            User user = (User) session.getAttribute(Const.SESSION_userpds);

            if (null == user) {
                String userName = session.getAttribute(Const.SESSION_USERNAME).toString();    //获取当前登录者loginname
                pd.put("USERNAME", userName);
                user = userDao.getByName(userName);

                session.setAttribute(Const.SESSION_userpds, user);
            }

            pdList.add(user);

            map.put("list", pdList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return AppUtil.returnObject(pd, map);
    }

    /**
     * 保存皮肤
     *
     * @param out
     */
    @RequestMapping(value = "/setSkin")
    public void setSkin(PrintWriter out) {
        PageData pd = this.getPageData();
        try {

            String skin = pd.getString("skin");

            //shiro管理的session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();

            String userName = session.getAttribute(Const.SESSION_USERNAME).toString();//获取当前登录者loginname
            userDao.setSkin(skin, userName);

            session.removeAttribute(Const.SESSION_userpds);
            session.removeAttribute(Const.SESSION_USERROL);
            out.write("success");
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 去编辑邮箱页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editEmail")
    public ModelAndView editEmail() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        mv.setViewName("system/head/edit_email");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 去发送短信页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goSendSms")
    public ModelAndView goSendSms() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        mv.setViewName("system/head/send_sms");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 发送短信
     *
     * @return
     */
    @RequestMapping(value = "/sendSms")
    @ResponseBody
    public Object sendSms() {
        PageData pd = new PageData();
        pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = "ok";        //发送状态
        int count = 0;            //统计发送成功条数
        int zcount = 0;            //理论条数


        List<PageData> pdList = new ArrayList<PageData>();

        String PHONEs = pd.getString("PHONE");                    //对方邮箱
        String CONTENT = pd.getString("CONTENT");                //内容
        String isAll = pd.getString("isAll");                    //是否发送给全体成员 yes or no
        String TYPE = pd.getString("TYPE");                        //类型 1：短信接口1   2：短信接口2
        String fmsg = pd.getString("fmsg");                        //判断是系统用户还是会员 "appuser"为会员用户


        if ("yes".endsWith(isAll)) {
            // TODO 发短信
        } else {
            PHONEs = PHONEs.replaceAll("；", ";");
            PHONEs = PHONEs.replaceAll(" ", "");
            String[] arrTITLE = PHONEs.split(";");
            zcount = arrTITLE.length;
            try {
                for (int i = 0; i < arrTITLE.length; i++) {
                    if (SysUtils.checkMobileNumber(arrTITLE[i])) {            //手机号式不对就跳过
                        if ("1".equals(TYPE)) {
//                            SmsUtil.sendSms1(arrTITLE[i], CONTENT);        //调用发短信函数1
                        } else {
//                            SmsUtil.sendSms2(arrTITLE[i], CONTENT);        //调用发短信函数2
                        }
                        count++;
                    } else {
                        continue;
                    }
                }
                msg = "ok";
            } catch (Exception e) {
                msg = "error";
            }
        }
        pd.put("msg", msg);
        pd.put("count", count);                        //成功数
        pd.put("ecount", zcount - count);                //失败数
        pdList.add(pd);
        map.put("list", pdList);
        return AppUtil.returnObject(pd, map);
    }

    /**
     * 去发送电子邮件页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goSendEmail")
    public ModelAndView goSendEmail() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        mv.setViewName("system/head/send_email");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 发送电子邮件
     *
     * @return
     */
    @RequestMapping(value = "/sendEmail")
    @ResponseBody
    public Object sendEmail() {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = "ok";        //发送状态
        int count = 0;            //统计发送成功条数
        int zcount = 0;            //理论条数

        try {

            //读取邮件配置
            String strEMAIL = configAPI.getByCode(Const.EMAIL).getValue();

            List<PageData> pdList = new ArrayList<PageData>();

            String toEMAIL = pd.getString("EMAIL");                    //对方邮箱
            String TITLE = pd.getString("TITLE");                    //标题
            String CONTENT = pd.getString("CONTENT");                //内容
            String TYPE = pd.getString("TYPE");                        //类型
            String isAll = pd.getString("isAll");                    //是否发送给全体成员 yes or no

            String fmsg = pd.getString("fmsg");                        //判断是系统用户还是会员 "appuser"为会员用户

            if (null != strEMAIL && !"".equals(strEMAIL)) {
                String strEM[] = strEMAIL.split(",fh,");
                // TODO 发邮件
            } else {
                msg = "error";
            }
            pd.put("msg", msg);
            pd.put("count", count);                        //成功数
            pd.put("ecount", zcount - count);                //失败数
            pdList.add(pd);
            map.put("list", pdList);

        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return AppUtil.returnObject(pd, map);
    }

    /**
     * 去系统设置页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goSystem")
    public ModelAndView goEditEmail() {

        ModelAndView mv = this.getModelAndView();
        try {
            PageData pd = this.getPageData();
            pd.put("SYSNAME", configAPI.getByCode(Const.SYSNAME).getValue());     //读取系统名称
            pd.put("COUNTPAGE", configAPI.getByCode(Const.PAGE).getValue());         //读取每页条数
            String strEMAIL = configAPI.getByCode(Const.EMAIL).getValue();         //读取邮件配置
            String strSMS1 = configAPI.getByCode(Const.SMS1).getValue();             //读取短信1配置
            String strSMS2 = configAPI.getByCode(Const.SMS2).getValue();             //读取短信2配置
            String strFWATERM = configAPI.getByCode(Const.FWATERM).getValue();     //读取文字水印配置
            String strIWATERM = configAPI.getByCode(Const.IWATERM).getValue();     //读取图片水印配置
            pd.put("Token", configAPI.getByCode(Const.WEIXIN).getValue());         //读取微信配置
            String strWEBSOCKET = configAPI.getByCode(Const.WEBSOCKET).getValue();//读取WEBSOCKET配置

            if (null != strEMAIL && !"".equals(strEMAIL)) {
                String strEM[] = strEMAIL.split(",fh,");
                if (strEM.length == 4) {
                    pd.put("SMTP", strEM[0]);
                    pd.put("PORT", strEM[1]);
                    pd.put("EMAIL", strEM[2]);
                    pd.put("PAW", strEM[3]);
                }
            }

            if (null != strSMS1 && !"".equals(strSMS1)) {
                String strS1[] = strSMS1.split(",fh,");
                if (strS1.length == 2) {
                    pd.put("SMSU1", strS1[0]);
                    pd.put("SMSPAW1", strS1[1]);
                }
            }

            if (null != strSMS2 && !"".equals(strSMS2)) {
                String strS2[] = strSMS2.split(",fh,");
                if (strS2.length == 2) {
                    pd.put("SMSU2", strS2[0]);
                    pd.put("SMSPAW2", strS2[1]);
                }
            }

            if (null != strFWATERM && !"".equals(strFWATERM)) {
                String strFW[] = strFWATERM.split(",fh,");
                if (strFW.length == 5) {
                    pd.put("isCheck1", strFW[0]);
                    pd.put("fcontent", strFW[1]);
                    pd.put("fontSize", strFW[2]);
                    pd.put("fontX", strFW[3]);
                    pd.put("fontY", strFW[4]);
                }
            }

            if (null != strIWATERM && !"".equals(strIWATERM)) {
                String strIW[] = strIWATERM.split(",fh,");
                if (strIW.length == 4) {
                    pd.put("isCheck2", strIW[0]);
                    pd.put("imgUrl", strIW[1]);
                    pd.put("imgX", strIW[2]);
                    pd.put("imgY", strIW[3]);
                }
            }
            if (null != strWEBSOCKET && !"".equals(strWEBSOCKET)) {
                String strIW[] = strWEBSOCKET.split(",fh,");
                if (strIW.length == 4) {
                    pd.put("WIMIP", strIW[0]);
                    pd.put("WIMPORT", strIW[1]);
                    pd.put("OLIP", strIW[2]);
                    pd.put("OLPORT", strIW[3]);
                }
            }

            mv.setViewName("system/head/sys_edit");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * 保存系统设置1
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveSys")
    public ModelAndView saveSys() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();


        ConfigEntity entity = new ConfigEntity();

        //写入系统名称
        entity.setCode(Const.SYSNAME);
        entity.setValue(pd.getString("SYSNAME"));
        configAPI.updateByCode(entity);

        //写入每页条数
        entity.setCode(Const.PAGE);
        entity.setValue(pd.getString("COUNTPAGE"));
        configAPI.updateByCode(entity);

        //写入邮件服务器配置
        entity.setCode(Const.EMAIL);
        entity.setValue(pd.getString("SMTP") + ",fh," + pd.getString("PORT") + ",fh," + pd.getString
                ("EMAIL") + ",fh," + pd.getString("PAW"));
        configAPI.updateByCode(entity);

        //写入短信1配置
        entity.setCode(Const.SMS1);
        entity.setValue(pd.getString("SMSU1") + ",fh," + pd.getString("SMSPAW1"));
        configAPI.updateByCode(entity);

        //写入短信2配置
        entity.setCode(Const.SMS2);
        entity.setValue(pd.getString("SMSU2") + ",fh," + pd.getString("SMSPAW2"));
        configAPI.updateByCode(entity);

        mv.addObject("msg", "OK");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 去代码生成器页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goProductCode")
    public ModelAndView goProductCode() throws Exception {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("system/head/productCode");
        return mv;
    }

}
